package cn.com.se.sharepictrue.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;

/**
 * Created by KIDNG on 2015/12/17.
 */
public class DoubleClickExit {
    private final Activity mActivity;
    private boolean mIsOnKeyBacking;
    private Handler mHandler;
    private Toast mBackToast;

    public DoubleClickExit(Activity activity) {
        mActivity = activity;
        mHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * Activity onKeyDown事件
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode != KeyEvent.KEYCODE_BACK) {
            return false;
        }

        if (mIsOnKeyBacking) {
            mHandler.removeCallbacks(mOnBackTimeRunnable);
            if (mBackToast != null) {
                mBackToast.cancel();
            }

            // 退出
            try {
                // 杀死该应用进程
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(0);
            } catch (Exception e) {
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(0);
            }
        } else {
            //第一次点击back
            mIsOnKeyBacking = true;
            if (mBackToast == null) {
                mBackToast = Toast.makeText(mActivity, "再点一次退出", Toast.LENGTH_LONG);
            }

            mBackToast.show();
            mHandler.postDelayed(mOnBackTimeRunnable, 2000);
        }
        return true;
    }

    private Runnable mOnBackTimeRunnable = new Runnable() {

        @Override
        public void run() {
            mIsOnKeyBacking = false;
            if (mBackToast != null) {
                mBackToast.cancel();
            }
        }
    };

}
